package hn.cch.spring_async_call.configuration;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 使用@Async指定默认线程池
 */
@EnableAsync
@Configuration
public class AsyncConfiguration {


    /**
     * 自定义异步线程池
     * 默认情况：Initializing ExecutorService 'applicationTaskExecutor'
     * 测试证明Async注解是否添加value属性都会使用自定义线程池
     *
     * @return
     */
    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        // 线程名称前缀
        threadPoolTaskExecutor.setThreadNamePrefix("async_");
        // 线程池核心线程数
        threadPoolTaskExecutor.setCorePoolSize(4);
        // 线程池最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(8);
        // 线程存活时间
        threadPoolTaskExecutor.setKeepAliveSeconds(60);
        // 队列最大容量
        threadPoolTaskExecutor.setQueueCapacity(100);
        // 设置拒绝策略
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 单独使用要初始化
        // threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }
}
